import React, {useEffect, useState} from 'react';
import {useQuery} from "../Helpers";
import axios from "axios";
import LoadingSpinner from "../components/LoadingSpinner";
import EmptyResultsMessage from "../components/EmptyResultsMessage";
import PostList from "./PostList";
import Pagination from "../components/Pagination";
import InlineError from "../components/InlineError";
import * as errmsg from '../constants'

const HomePage = () => {
    const [loading, setLoading] = useState(true);
    const [posts, setPosts] = useState([])
    const [error, setError] = useState('')

    // 总页码
    const [numPages, setNumPages] = useState(1)

    // 默认显示第一页
    const [page, setPage] = useState(1)

    let query = useQuery()

    // ComponentDidMount
    // 每次页面挂载后执行
    useEffect(() => {
        let page = query.get('page')
        if (!page)
            page = 1
        else
            page = parseInt(page)

        if (page < 1)
            page = 1

        if (page > numPages)
            page = numPages
        setPage(page)
    }, [setPage, numPages, query])

    useEffect(() => {
        const getPosts = async () => {
            axios.get(`/api/v1/posts/?page=${page}`)
                .then(response => {
                    setLoading(false)
                    setPosts(response.data.results)
                    setNumPages(response.data.num_pages)
                    // setError('')
                })
                .catch(err => {
                    setLoading(false)
                    setPosts([])
                    setNumPages(1)
                    setError(errmsg.CUSTOM_ERROR_MSG)
                })
        }
        getPosts()

    }, [page])

    if (loading) return <LoadingSpinner/>
    if (error) return <InlineError error={error}/>
    if (posts.length === 0) return <EmptyResultsMessage/>

    return (
        <div className="col-lg-8">
            <PostList posts={posts}/>
            <Pagination page={page} numPages={numPages}/>
        </div>
    )
};

export default HomePage;